package collection;

import org.junit.Test;

import java.util.*;

public class CollectionsTest {

    @Test
    public void test1() {

        List<String> list = new ArrayList<>();
        list.add("b");
        list.add("c");
        list.add("a");

        // 反转
        Collections.reverse(list);

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    }

    @Test
    public void test2() {
        List<String> list = new ArrayList<>();
        list.add("b");
        list.add("c");
        list.add("a");

        // 随机排序
        Collections.shuffle(list);

        for (String s : list) {
            System.out.println(s);
        }
    }


    @Test
    public void test3() {
        List<String> list = new ArrayList<>();
        list.add("b");
        list.add("c");
        list.add("a");

        // 顺序
        Collections.sort(list);

        // 逆序
        Collections.reverse(list);

        for (String s : list) {
            System.out.println(s);
        }
    }

    @Test
    public void test4() {

        List<V2> list = new ArrayList<>();
        list.add(new V2(9));
        list.add(new V2(8));
        list.add(new V2(7));
        list.add(new V2(7));

        Collections.sort(list, new Comparator<V2>() {
            @Override
            public int compare(V2 o1, V2 o2) {
                return Integer.compare(o1.getId() , o2.getId());
            }
        });

        System.out.println(list);

        int frequency = Collections.frequency(list, new V2(7));
        System.out.println(frequency);

    }

    @Test
    public void test5() {
        List<String> src = new ArrayList<>();
        src.add("b");
        src.add("c");
        src.add("a");

        // 错误写法
//        List<String> desc = new ArrayList<>();

        List<String> desc = Arrays.asList(new String[src.size()]);
        Collections.copy(desc,src);

        System.out.println(desc);
    }
}

class V2 {
    private int id;

    public V2(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        V2 v2 = (V2) o;
        return id == v2.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "V2{" +
                "id=" + id +
                '}';
    }
}
